﻿using AutoMapper;
using B.S.DataBase.MyProject.Domain;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using B.S.DataBase.MyWrite.API.Appicant.Command.Approval;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Validations;

namespace B.S.DataBase.MyWrite.API.Appicant.CommandHandler.Approval
{
    /// <summary>
    /// 审批添加
    /// </summary>
    public class AddApprovalCommandHandler : IRequestHandler<AddApprovalCommand, APIResult<object>>
    {
        private readonly IBaseRepository<LeaveApplication> leaveappRep;
        private readonly IBaseRepository<ApprovalRecord> recordRep;
        private readonly IMapper mapper;

        public AddApprovalCommandHandler(IBaseRepository<LeaveApplication> leaveappRep,IBaseRepository<ApprovalRecord> recordRep,IMapper mapper)
        {
            this.leaveappRep = leaveappRep;
            this.recordRep = recordRep;
            this.mapper = mapper;
        }

        public async Task<APIResult<object>> Handle(AddApprovalCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            LeaveApplication leave=new LeaveApplication();
            leave.ApplicantName = request.ApplicantName;
            leave.DepartMentid = request.DepartMentid;
            leave.LeaveType=request.LeaveType;
            leave.StartTime = request.StartTime.AddHours(8);
            leave.EndTime = request.EndTime.AddHours(8);
            leave.TimeSpan = request.TimeSpan;
            leave.ReasonLeave=request.ReasonLeave;
            leave.RegistrationTime=request.RegistrationTime;
            leave.DepartmentHead=request.DepartmentHead;
            leave.Status=(int)FlowStatus.待审批;
            leave.CreateName=request.CreateName;
            leave.CreateTime = DateTime.Now;
            
           await leaveappRep.Add(leave);

            ApprovalRecord record = new ApprovalRecord();
            record.DepartmentId = leave.DepartMentid;
            record.DepartmentHeadId=request.DepartmentHeadId;
            record.LeaveId=leave.LeaveId;
            record.ApproverId = request.userId;
            record.ApproverName = leave.ApplicantName;
            record.Status = leave.Status.ToString();
            record.ApprovalTime = leave.CreateTime;
            record.Comment = "";

           await recordRep.Add(record);

            result.Code = APIEnum.操作成功;
            result.Msg = APIEnum.操作成功.ToString();
            
            return await Task.FromResult(result);


        }
    }
}
